package org.erp.store.controller;

import org.erp.common.annotation.StockLockBatch;
import org.erp.common.domain.Result;
import org.erp.common.enums.DeviceInventoryEvent;
import org.erp.common.page.DataPageResp;
import org.erp.common.page.PageQueryModel;
import org.erp.store.domain.entity.DeviceInventory;
import org.erp.store.domain.bo.DeviceInventoryBo;
import org.erp.store.domain.dto.BatchDeviceInventoryDto;
import org.erp.store.domain.dto.BatchDeviceInventoryResponseDto;
import org.erp.store.domain.dto.InventoryDto;
import org.erp.common.exception.ServiceException;
import org.erp.store.domain.vo.DeviceInventoryDetailsVo;
import org.erp.store.domain.vo.DeviceInventoryVo;
import org.erp.common.annotation.Idempotent;
import org.erp.store.service.BatchDeviceInventoryService;

import org.erp.store.service.DeviceInventoryLogicService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.ArrayList;
import java.util.List;

import static org.erp.common.domain.Result.success;

/**
 * 设备库存控制器
 *
 * @author dingding
 * @since 2025-11-12
 */
@RestController
@RequestMapping("/inventory")
@Validated
public class DeviceInventoryController {


    
    @Resource
    private BatchDeviceInventoryService batchDeviceInventoryService;

    @Resource
    private DeviceInventoryLogicService deviceInventoryQueryLogicService;


    /**
     * 获取所有数据
     *
     * @param deviceInventoryBo 筛选条件
     * @return 所有数据
     */
    @GetMapping("/getListByPage")
    public Result<DataPageResp<DeviceInventoryVo>> getListByPage(DeviceInventoryBo deviceInventoryBo){
        PageQueryModel<DeviceInventoryVo> queryModel = deviceInventoryQueryLogicService.getListByPage(deviceInventoryBo);
        return success(DataPageResp.of(queryModel.getTotal(), queryModel.getDataList()));
    }

    /**
     * 根据背贴码获取设备详情
     *
     * @param productCode 背贴码
     * @return 设备详情
     */
    @GetMapping("getDetailsByCode")
    public Result<DeviceInventoryDetailsVo> getDetailsByCode(String productCode){
        return success(deviceInventoryQueryLogicService.getDetailsByCode(productCode));
    }



    /**
     * 批量入库
     *
     * @return
     */
    @PostMapping("/batch/storage")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> storage(@RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.STORAGE);
        return batchUpdateStatus(dto);
    }



    /**
     * 批量调拨（从入库到调拨中）
     */
    @PostMapping("/batch/allocate")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchAllocate(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.ALLOCATE);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量接驳完成（从调拨中到已接驳）
     */
    @PostMapping("/batch/handover")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchHandover(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.HANDOVER);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量驳回（从调拨中到驳回）
     */
    @PostMapping("/batch/reject")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchReject(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.REJECT);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量再次入库（从驳回到入库）
     */
    @PostMapping("/batch/reInbound")
    @Idempotent
    @StockLockBatch(listField = "inventoryList", idField = "inventoryId")
    public Result<BatchDeviceInventoryResponseDto> batchReInbound(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.REJECT_TO_INBOUND);
        return batchUpdateStatus(dto);
    }

     /**
      * 批量撤销驳回（从驳回到调拨中）
      */
     @PostMapping("/batch/cancelReject")
     public Result<BatchDeviceInventoryResponseDto> batchCancelReject(@Valid @RequestBody BatchDeviceInventoryDto dto) {
         dto.setTargetEvent(DeviceInventoryEvent.CANCEL_REJECT);
         return batchUpdateStatus(dto);
     }

    /**
     * 批量售出（从已接驳到已售出）
     */
    @PostMapping("/batch/sell")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchSell(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.SELL);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量申请返库（从已接驳到待返库）
     */
    @PostMapping("/batch/requestReturn")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchRequestReturn(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.REQUEST_RETURN);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量确认返库（从待返库到已入库）
     */
    @PostMapping("/batch/confirmReturn")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchConfirmReturn(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.RETURN_TO_INBOUND);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量申请退库（从已接驳到待退库）
     */
    @PostMapping("/batch/requestRefund")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchRequestRefund(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.REQUEST_REFUND);
        return batchUpdateStatus(dto);
    }

    /**
     * 批量确认退库（从待退库到已退库）
     */
    @PostMapping("/batch/confirmRefund")
    @Idempotent
    public Result<BatchDeviceInventoryResponseDto> batchConfirmRefund(@Valid @RequestBody BatchDeviceInventoryDto dto) {
        dto.setTargetEvent(DeviceInventoryEvent.CONFIRM_REFUND);
        return batchUpdateStatus(dto);
    }




    public Result<BatchDeviceInventoryResponseDto> batchUpdateStatus(BatchDeviceInventoryDto dto) {
        try {
            BatchDeviceInventoryResponseDto response = batchDeviceInventoryService.batchUpdateStatusStrategic(dto);
            // 根据成功数量返回不同的响应
            if (response.getSuccessCount().equals(response.getTotalCount())) {
                return Result.success(response, "批量状态更新成功");
            } else if (response.getSuccessCount() > 0) {
                return Result.success(response, "批量状态更新部分成功，成功" + response.getSuccessCount() + "条，失败" + response.getFailedCount() + "条");
            } else {
                return Result.error("批量状态更新失败");
            }
        } catch (ServiceException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("批量状态更新失败：" + e.getMessage());
        }
    }

   @GetMapping("/test")
    public Result<BatchDeviceInventoryResponseDto>  test(int size, String type){
       BatchDeviceInventoryDto batchStorageDto = new BatchDeviceInventoryDto();
       batchStorageDto.setOperateId(2L);
       batchStorageDto.setOperateName("lisi");
       List<DeviceInventory> deviceList=new ArrayList<>();
       for (int i = 0; i < size; i++) {
           DeviceInventory deviceInfoRemoteDto = new DeviceInventory();
           deviceInfoRemoteDto.setProductCode("Ph" +type+ i);
           deviceInfoRemoteDto.setOrderNo("Or" +type+ i);
           deviceInfoRemoteDto.setProductName("手机" + i);
           deviceInfoRemoteDto.setProductImei("IMEI" + i);
           deviceInfoRemoteDto.setProductColor("黑色");
           deviceInfoRemoteDto.setProductStorage("128G");
           deviceInfoRemoteDto.setCategoryId(1L);
           deviceInfoRemoteDto.setLevelId(1L);
           deviceInfoRemoteDto.setBrandId(1L);
           deviceInfoRemoteDto.setSeriesId(1L);
           deviceInfoRemoteDto.setModelId(1L);
           deviceInfoRemoteDto.setTenantId(1L);
           deviceInfoRemoteDto.setTenantName("租户1");
           deviceInfoRemoteDto.setProcurementPrice(1000);
           deviceInfoRemoteDto.setStoreId(1L);
           deviceInfoRemoteDto.setStoreName("仓库1");
           deviceList.add(deviceInfoRemoteDto);
       }
       batchStorageDto.setDeviceList(deviceList);
       Long startTime=System.currentTimeMillis();
       Result<BatchDeviceInventoryResponseDto> result= storage(batchStorageDto);
       long endTime=System.currentTimeMillis()-startTime;
       System.out.println("结束:"+endTime);
      return result;
    }

    @GetMapping("/test1")
    public Result<BatchDeviceInventoryResponseDto> test1(int size, int type){

        BatchDeviceInventoryDto dto = new BatchDeviceInventoryDto();
        dto.setOperateId(4L);
        dto.setOperateName("test");
        dto.setTransferUserId(3L);
        dto.setTransferUserName("王武");
        dto.setDeptId(2L);
        dto.setDeptName("部门2");
        List<InventoryDto> inventoryDtoList=new ArrayList<>();
        for (int i = 0; i < size; i++) {
            InventoryDto inventoryDto = new InventoryDto();
            int inventoryId = type+i;
            inventoryDto.setInventoryId(Integer.toUnsignedLong(inventoryId));
            inventoryDtoList.add(inventoryDto);
        }
        dto.setInventoryList(inventoryDtoList);
        Long startTime=System.currentTimeMillis();
        System.out.println("开始:"+startTime);
        Result<BatchDeviceInventoryResponseDto>  result=batchAllocate(dto);
        long endTime=System.currentTimeMillis()-startTime;
        System.out.println("结束:"+endTime);
        return result;
    }



     



}
